import { ColorPicker, type ColorPickerProps } from 'vue3-colorpicker'
import 'vue3-colorpicker/style.css'
import { defineComponent, nextTick, onMounted, reactive } from 'vue'
import type { PropType } from 'vue'
import type { JsonSchema, Slots } from '@/types/advertising/colorPicker'
import { ref } from 'vue'
interface IColorState {
  r: number
  g: number
  b: number
  alpha: number
  hex: string
}
export default defineComponent({
  inheritAttrs: true,
  props: {
    schema: {
      type: Object as PropType<JsonSchema>,
      default: () => ({})
    },
    slots: {
      type: Object as PropType<Slots>,
      default: () => null
    },
    changeFuncName: {
      type: String,
      default: ''
    }
  },
  setup(props, context) {
    const defaultColor = 'rgba(22, 93, 255, 0.82)'
    const gradientColor = 'linear-gradient(0deg, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 1) 100%)'
    const color = ref<string>('')
    const _props: ColorPickerProps = {
      lang: 'ZH-cn',
      disableAlpha: false,
      disableHistory: true,
      pickerType: 'chrome',
      format: 'rgb',
      pureColor: props?.schema?.defaultValue ?? defaultColor,
      gradientColor
    }

    const colorState = reactive<IColorState>({ r: 0, g: 0, b: 0, alpha: 1, hex: '000000' })
    const handleRgbaSplit = (color: string) => {
      if (!color) return
      try {
        const rgbaAttr = color.match(/[\d.]+/g)
        if (rgbaAttr && rgbaAttr.length > 3) {
          const data = rgbaAttr as unknown as number[]
          colorState.r = data[0]
          colorState.g = data[1]
          colorState.b = data[2]
          colorState.alpha = data[3]
          colorState.hex = data
            .slice(0, 3)
            .map((n) => {
              const res = Number(n).toString(16).toUpperCase()
              return res.length === 1 ? `0${res}` : res
            })
            .join('')
        }
      } catch (_) {
        //
      }
    }
    const handleColorChange = (v: string) => {
      color.value = v
      console.log('color.value: ', color.value)
      console.log('context: ', context.attrs)
      context.emit(props.changeFuncName, color.value)
    }
    onMounted(() => {
      nextTick(() => {
        if (props?.schema?.defaultValue) {
          handleRgbaSplit(props?.schema?.defaultValue as string)
        }
      })
    })
    return () => (
      <div class="color-picker__wrapper">
        {/* <span class="color-picker__label">{color.value}</span> */}
        <ColorPicker {..._props} onPureColorChange={(v) => handleColorChange(v)} />
        <div class="custom-bar flex justify-between items-center gap-x-2">
          <div class="text-center ">
            <div class="color-picker-current-color" style={{ 'background-color': `#${colorState.hex}` }}></div>
          </div>
        </div>
      </div>
    )
  }
})
